package com.pap.rbac.orgation.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.pap.base.controller.BaseController;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.jackson.JacksonUtilss;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.business.DisableFlagEnum;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.orgation.IOrganizationAgent;
import com.pap.rbac.agent.orgation.dto.OrganizationTreeNodeVO;
import com.pap.rbac.orgation.auto.entity.Organization;

@RestController
@RequestMapping("/v1/rbac/organization")
public class OrganizationController extends BaseController<Organization, IOrganizationAgent> {

	private static Logger logger  =  LoggerFactory.getLogger(OrganizationController.class);
	
	@Resource(name = "organizationAgent")
	@Override
	public void setService(IOrganizationAgent agent) {
		super.service = agent;
	}
	
	@RequestMapping(value = "/treejson", method = {RequestMethod.GET})
	public List<OrganizationTreeNodeVO> treeJSON(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId) {
		//  全局默认组织机构的顶层编码为 -1 
		String globalParentId = "-1";
		return service.organizationTreeJson(clientLicenseId, globalParentId);
	}
	
	/**
	 * 组织机构保存
	 * 必须输入参数为组织机构名称
	 */
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/add", method = {RequestMethod.POST} )
	public ResponseVO<Organization> add(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "addJSON", required = true) String addJSON) throws Exception {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Organization organization = objectMapper.readValue(addJSON, Organization.class);
		organization.setId(UUID.randomUUID().toString());
		
		
		if(organization != null && 
				StringUtilss.isNotEmpty(organization.getName())) {
			// 如果前端没有传递过来code值，则默认使用拼音代替
			if(StringUtilss.isEmpty(organization.getCode())) {
				organization.setCode(PinyinHelper.convertToPinyinString(organization.getName(), "", PinyinFormat.WITHOUT_TONE));
			}
			// 处理父级数据
			Organization parentOrganization = service.selectByPrimaryKey(organization.getParentId());
			if(parentOrganization != null) {
				// pathId
				if(StringUtilss.isNotEmpty(parentOrganization.getPathIds())) {
					organization.setPathIds(parentOrganization.getPathIds() + "," + parentOrganization.getId());
				} else {
					organization.setPathIds(parentOrganization.getId());
				}
				// pathCode
				if(StringUtilss.isNotEmpty(parentOrganization.getPathCodes())) {
					organization.setPathCodes(parentOrganization.getPathCodes() + "," + parentOrganization.getCode());
				} else {
					organization.setPathCodes(parentOrganization.getCode());
				}
				// pathName
				if(StringUtilss.isNotEmpty(parentOrganization.getPathNames())) {
					organization.setPathNames(parentOrganization.getPathNames() + "," + parentOrganization.getName());
				} else {
					organization.setPathNames(parentOrganization.getName());
				}
			} 
			organization.setDisableFlag(DisableFlagEnum.YES.getKey());
			organization.setCreateIp("0.0.0.0");
			organization.setCreateTime(DateUtils.getCurrDateTimeStr());
			organization.setCreateUser(loginUserId);
			organization.setClientLicenseId(clientLicenseId);
			organization.setParentId(StringUtilss.isNotEmpty(organization.getParentId()) == true ? organization.getParentId() : "-1");
			
			int operationInt = service.insertSelective(organization);
			
			return ResponseVO.successdata(operationInt);
			
		} else {
			return ResponseVO.validfail("入参异常，请判断是否含有组织机构名称");
		}

	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delete")
	public ResponseVO<Organization> delete(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "deleteJSON", required = true) String deleteJSON) throws Exception {

		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Organization organization = objectMapper.readValue(deleteJSON, Organization.class);
		if(organization != null && StringUtilss.isNotEmpty(organization.getId())) {
			Map<Object, Object> pathIdsMap = new HashMap<Object, Object>();
			pathIdsMap.put("pathIds", organization.getId());
			List<Organization> organizationList = service.selectListByMap(pathIdsMap);
			if(organizationList != null && organizationList.size() > 0) {
				return ResponseVO.validfail("请检查入参，此机构被其他机构所依赖!");
			} else {
				int operationInt = service.deleteByPrimaryKey(organization.getId());
				return ResponseVO.successdata(operationInt);
			}
		} else { 
			return ResponseVO.validfail("入参异常，请判断是否含有机构编码");
		}
	}

	@RequestMapping(value = "/deletebyid/{id}", method = {RequestMethod.DELETE})
	public ResponseVO<Organization> deleteById(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
										   @RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
											@PathVariable(value = "id") String id) throws Exception {

		Organization organization = new Organization();
		organization.setId(id);
		if(organization != null && StringUtilss.isNotEmpty(organization.getId())) {
			Map<Object, Object> pathIdsMap = new HashMap<Object, Object>();
			pathIdsMap.put("pathIds", organization.getId());
			List<Organization> organizationList = service.selectListByMap(pathIdsMap);
			if(organizationList != null && organizationList.size() > 0) {
				return ResponseVO.validfail("请检查入参，此机构被其他机构所依赖!");
			} else {
				int operationInt = service.deleteByPrimaryKey(organization.getId());
				return ResponseVO.successdata(operationInt);
			}
		} else {
			return ResponseVO.validfail("入参异常，请判断是否含有机构编码");
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/update", method = {RequestMethod.POST} )
	public ResponseVO<Organization> update(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "updateJSON", required = true) String updateJSON) 
					throws IOException, JsonParseException, JsonMappingException {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Organization organization = objectMapper.readValue(updateJSON, Organization.class);
		
		ResponseVO responseVO = service.updateAndCheckOrganization(organization, loginUserId);
		return responseVO;
	}

    @RequestMapping(value = "/transaction")
    public int transaction(HttpServletRequest request, String jsonData) {
    	Organization organization1 = new Organization();
    	organization1.setId(UUID.randomUUID().toString());
    	
    	Organization organization2 = new Organization();
    	
    	List<Organization> list = new ArrayList<Organization>();
    	list.add(organization1);
    	list.add(organization2);
    	
    	return service.insertSelectiveList(list);
    }
    
    
}
